﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.Team;
using SportsPlatform.Helpers;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.SportBusiness.Team;
using SportsPlatform.SportBusiness.ISportBusiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 团队表
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class TeamService : SportsPlatformAppServiceBase, ITeamService
    {
        /// <summary>
        /// 团队仓储
        /// </summary>
        private readonly IRepository<Team, Guid> _teamRepository;

        /// <summary>
        /// 团队用户仓储
        /// </summary>
        private readonly IRepository<TeamUser, Guid> _teamUserRepository;

        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IRepository<Employee, Guid> _employeeRepository;

        public TeamService(IRepository<Team, Guid> teamRepository, IRepository<TeamUser, Guid> teamUserRepository,
            IRepository<Employee, Guid> employeeRepository, IHttpContextAccessor context) : base(context)
        {
            _teamRepository = teamRepository;
            _employeeRepository = employeeRepository;
            _teamUserRepository = teamUserRepository;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<TeamByUserListDto>> GetTeamList(TeamByUserListQuery Query)
        {
            try
            {
                if ((!string.IsNullOrEmpty(Query.RealName)) && (!string.IsNullOrEmpty(Query.IDNumber)))
                {
                    var empinfo = await _employeeRepository.FirstOrDefaultAsync(info => info.RealName.Equals(Query.RealName) && info.IDNumber.Equals(Query.IDNumber));
                    if (empinfo == null)
                    {
                        return new PagePagingDto<TeamByUserListDto>()
                        {
                            IsSuccess = false,
                            Code = (int)HttpResultCode.Fail,
                            Message = "未查询到用户信息！",
                            Data = null,
                            TotalCount = 0,
                            TotalPage = 0
                        };
                    }
                    else {
                        Query.UserId = empinfo.Id;
                    }
                }

                var teamusers = await _teamUserRepository.GetAllListAsync(tu => tu.EmployeeId == Query.UserId && tu.IsDeleted == false);
                var ListDtos = await _teamRepository.GetAllListAsync(t => t.IsDeleted == false);
                List<TeamByUserListDto> ListDto = new List<TeamByUserListDto>();

                teamusers.ForEach(tu =>
                {
                    var team = ListDtos.FirstOrDefault(t => t.Id == tu.TeamId);
                    ListDto.Add(new TeamByUserListDto
                    {
                        Id = team.Id,
                        TeamName = team.TeamName,
                        TeamNum = team.TeamNum,
                    });
                });
               
                return new PagePagingDto<TeamByUserListDto>()
                {
                    IsSuccess = true,
                    Code = (int)HttpResultCode.Success,
                    Message = "查询成功",
                    Data = ListDto,
                };
            }
            catch (Exception ex)
            {
                return new PagePagingDto<TeamByUserListDto>()
                {
                    IsSuccess = false,
                    Code = (int)HttpResultCode.Error,
                    Message = ex.Message,
                    Data = null,
                    TotalCount = 0,
                    TotalPage = 0
                };
            }
        }

        /// <summary>
        /// 添加团队
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddTeam(AddTeamQuery Query)
        {
            try
            {
                #region 比赛规则信息
                Team info = new Team();
                info.TeamName = Query.TeamName;
                info.TeamNum = 0;
                info.CreateTime = DateTime.Now;
                info.CreateUserId = Query.EmployeeId;
                info.IsDeleted = false;
                #endregion
                var teamId = await _teamRepository.InsertAndGetIdAsync(info);

                var employee = await _employeeRepository.GetAsync(Query.EmployeeId);
                if (!employee.IsNullAndEmpty())
                {
                    var tuser = new TeamUser();
                    tuser.TeamId = teamId;
                    tuser.EmployeeId = employee.Id;
                    var teamUser = await _teamUserRepository.InsertAsync(tuser);
                    return new BaseResultDto()
                    {
                        IsSuccess = true,
                        Code = HttpResultCode.Success,
                        Message = "保存成功"
                    };
                }
                else
                {
                    return new BaseResultDto()
                    {
                        IsSuccess = false,
                        Code = HttpResultCode.NotData,
                        Message = "未查询到当前用户"
                    };
                }

            }
            catch (Exception ex)
            {
                return new BaseResultDto()
                {
                    IsSuccess = false,
                    Code = HttpResultCode.Error,
                    Message = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取团队内人员信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetTeamUserListDto>> GetTeamUserList(GetTeamUserListQuery query)
        {
            ResultListDto<GetTeamUserListDto> resultListDto = new ResultListDto<GetTeamUserListDto>();
            try {
                var teamUserList = await _teamUserRepository.GetAllListAsync(info => info.TeamId == query.TeamId && info.IsDeleted == false);
                if (teamUserList != null && teamUserList.Count > 0)
                {
                    List<GetTeamUserListDto> dtos = new List<GetTeamUserListDto>();
                    var employeelist = await _employeeRepository.GetAllListAsync();
                    foreach (var item in teamUserList)
                    {
                        GetTeamUserListDto dto = new GetTeamUserListDto();
                        var empinfo = employeelist.FirstOrDefault(info=>info.Id==item.EmployeeId);
                        dto.EmployeeId = empinfo.Id;
                        dto.RealName = empinfo.RealName;
                        dto.IDNumber= empinfo.IDNumber;
                        dto.Phone = empinfo.Phone;
                        dtos.Add(dto);
                    }
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = dtos;
                }
                else {
                    resultListDto.IsSuccess = false;
                    resultListDto.Code = HttpResultCode.NotData;
                    resultListDto.Message = "未查到数据！";
                }
            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString() ;
            }
            return resultListDto;
        }
    }
}
